package com.lixin.web.aspect;

import com.lixin.exception.ParamsException;
import com.lixin.utils.JsonUtils;
import com.lixin.web.netty.NettyUtil;
import com.lixin.web.webSocket.ChatManager;
import com.lixin.web.webSocket.NotificationManager;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;

/**
 * Description:
 * Copyright:   Copyright (c)2023
 * Company:     sci
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2023-08-09 03:07:56
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2023-08-09     张李鑫                     1.0         1.0 Version
 */
@Aspect
@Slf4j
@Component
public class LogAspect {
    /**
     * 排除通知类 因为是异步的 在交互结束以后 threadlocal就已经被释放了。所以不需要打日志并且在消息的存储也有日志相关的记录
     *
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.lixin.web.webSocket.impl.*.*(..))&& !execution(* com.lixin.web.webSocket.NotificationManager.*(..))")
    public Object parameterCheckLogAspect(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object[] args = joinPoint.getArgs();
        parameterCheck(args);
        Integer userId = NettyUtil.getUserId();
        String methodName = joinPoint.getSignature().getName();
        log.info("Before executing method: {} userId:{} params:{}", methodName, userId, args.length != 0 ? JsonUtils.toJsonString(args[0]) : "params is empty");
        Object result = joinPoint.proceed();
        log.info("After executing method: :{} Execution time:{}  userId:{}", methodName, System.currentTimeMillis() - start, userId);
        return result;
    }

    public void parameterCheck(Object[] args) {
        boolean hasParams = args.length != 0;
        if (hasParams && args[0] == null) {
            throw new ParamsException();
        }
    }

}
